import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCInsert {
    public static void main(String[] args)  throws SQLException{
        Scanner scan = new Scanner(System.in);
        //1、创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();//向上转型
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/people_2?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("991218zf");
        //2、和数据库服务器建立联接
        Connection connection= dataSource.getConnection() ;
        //3、构造SQL语句
        System.out.println("请输入学生姓名：");
        String name = scan.next();
        System.out.println("请输入学生的学号:");
        int id = scan.nextInt();
        String sql = "insert into student_4 values(?,?)";
//        String sql = "delete from student where id = ?";
//        String sql = "update student set id = ? where name = ?";
        PreparedStatement statement = connection.prepareStatement(sql);//进行预编译
        statement.setInt(1,id);//表示将第一个？替换成id的值
        statement.setString(2,name);//表示将第二个？替换成name的值
        //这个打印需要加到拼接数据之后
        System.out.println(statement);
        //4、执行SQL语句
        int ret = statement.executeUpdate();
        System.out.println("ret = "+ret);
        //5、释放必要的资源
        statement.close();
        connection.close();
    }
}
